<script setup defer async lang="ts">
import { reactive, onMounted, ref } from 'vue'
import { API_IMG_URL } from '@/utils/apiUrl'
import { useI18n } from 'vue-i18n'
import { formatDate } from '@/utils/utils'
import { systemMessage, systemMessageDetail, notice } from '@/api/user'
import { useSwipeHandlers } from '@/utils/useSwipeHandlers'

const { t } = useI18n()
const imgUrl = ref(API_IMG_URL())

// 
interface MessageItem {
  ID: number
  title: string
  content: string
  type: number
  status: number
  CreatedAt: string
}

const baseData = reactive({
  type: 0,
  showDetail: false,
  loading: false,
  page: 1,
  dataList: [] as MessageItem[],
  details: {} as MessageItem,
  aircraftUrl: uni.getStorageSync('aircraftUrl'),
})

const getDetial = async (index: number) => {
  if (baseData.type) {
    let params: any = {
      id: baseData.dataList[index].ID,
    }
    
    try {
      const res = await systemMessageDetail(params)
      if (res.code === 0) {
        baseData.showDetail = true
        baseData.details = res.data
        baseData.dataList[index].status = 2
      }
    } catch (error) {
      console.error(':', error)
      uni.showToast({
        title: '',
        icon: 'none',
      })
    }
  } else {
    baseData.details = baseData.dataList[index]
    baseData.showDetail = true
  }
}

const getList = async () => {
  baseData.loading = true
  uni.showLoading({
    title: t('Loading'),
    icon: 'none',
  })
  
  let params: any = {
    page: baseData.page,
    pageSize: 20,
  }
  
  try {
    const res = await systemMessage(params)
    if (res.code === 0) {
      if (res.data.list.length > 0) {
        baseData.dataList = baseData.dataList.concat(res.data.list)
        baseData.page++
      }
    } else {
      uni.showToast({
        title: res.msg,
        icon: 'none',
      })
    }
  } catch (error) {
    console.error(':', error)
    uni.showToast({
      title: '',
      icon: 'none',
    })
  } finally {
    baseData.loading = false
    uni.hideLoading()
  }
}

const getNotice = async () => {
  baseData.loading = true
  uni.showLoading({
    title: t('Loading'),
    icon: 'none',
  })
  
  try {
    const res = await notice()
    if (res.code === 0) {
      if (res.data.length > 0) {
        baseData.dataList = baseData.dataList.concat(res.data)
      }
    } else {
      uni.showToast({
        title: res.msg,
        icon: 'none',
      })
    }
  } catch (error) {
    console.error(':', error)
    uni.showToast({
      title: '',
      icon: 'none',
    })
  } finally {
    baseData.loading = false
    uni.hideLoading()
  }
}

const changTab = (e: any) => {
  console.log(e)
  baseData.dataList = []
  baseData.page = 1
  baseData.type = e.index
  if (baseData.type) {
    getList()
  } else {
    getNotice()
  }
}

const leftClick = () => {
  const pages = getCurrentPages()
  if (pages.length <= 1) {
    history.back()
  } else {
    uni.navigateBack()
  }
}

// 
const handleSwipeRight = () => {
  const pages = getCurrentPages()
  if (pages.length <= 1) {
    history.back()
  } else {
    uni.navigateBack()
  }
}

useSwipeHandlers(handleSwipeRight)

onMounted(() => {
  // 
  uni.setNavigationBarTitle({
    title: 'Ttask!' + t('Earn money so easy') + '!', // 
  })
  changTab({ index: 0 })
})
</script>

<template>
  <view class="message-container">
    <!--  -->
    <view class="bg-decoration">
      <view class="circle circle-1"></view>
      <view class="circle circle-2"></view>
      <view class="circle circle-3"></view>
      <view class="floating-shape shape-1">📨</view>
      <view class="floating-shape shape-2">💌</view>
      <view class="floating-shape shape-3">🔔</view>
    </view>

    <!--  -->
    <up-navbar :title="t('Message')" @leftClick="leftClick" :autoBack="false">
      <template #left>
        <view class="nav-back-btn">
          <image class="back-icon" src="../../../static/img/left.png"></image>
        </view>
      </template>
    </up-navbar>

    <!--  -->
    <view class="tabs-section">
      <up-tabs :list="[{ name: t('Notification') }, { name: t('System Messages') }]" @change="changTab" lineColor="#667eea" :activeStyle="{
        color: '#667eea',
        fontWeight: 'bold',
        transform: 'scale(1.05)'
      }"></up-tabs>
    </view>

    <!--  -->
    <view class="message-list-section">
      <view class="list-container">
        <!--  -->
        <view 
          v-for="(item, index) in baseData.dataList" 
          :key="index"
          class="message-item"
          @click="getDetial(index)"
        >
          <!--  -->
          <view class="item-icon">
            <view class="icon-circle">
              <text class="icon-text">💬</text>
            </view>
          </view>

          <!--  -->
          <view class="item-content">
            <!--  -->
            <view class="message-title">{{ item.title }}</view>

            <!--  -->
            <view 
              v-if="baseData.type == 1"
              class="message-preview"
            >
              <rich-text :nodes="item.content ? item.content : '-'"></rich-text>
            </view>
            <view 
              v-if="baseData.type == 0 && item.type == 1"
              class="message-preview"
            >
              <rich-text :nodes="item.content ? item.content : '-'"></rich-text>
            </view>

            <!--  -->
            <view class="message-time">{{ formatDate(item.CreatedAt) }}</view>
          </view>

          <!--  -->
          <view class="item-status">
            <view v-show="baseData.type == 1 && item.status == 1" class="unread-indicator"></view>
          </view>
        </view>

        <!--  -->
        <view v-if="baseData.dataList.length === 0 && !baseData.loading" class="empty-state">
          <text class="empty-icon">📭</text>
          <text class="empty-text">{{ t('No Messages') }}</text>
        </view>

        <!--  -->
        <view v-if="baseData.loading" class="bottom-status">
          <text class="loading-text">{{ t('Loading') }}...</text>
        </view>
      </view>
    </view>

    <!--  -->
    <up-popup v-model="baseData.showDetail" mode="center" :width="680" :height="800" closeable round="20">
      <view class="detail-container">
        <view class="detail-header">
          <view class="detail-title">{{ baseData.details.title }}</view>
          <view class="detail-time">{{ formatDate(baseData.details.CreatedAt) }}</view>
        </view>
        
        <view class="detail-content">
          <view v-show="baseData.type == 1" class="content-text">
            <rich-text :nodes="baseData.details.content ? baseData.details.content : '-'"></rich-text>
          </view>
          <view v-show="baseData.type == 0 && baseData.details.type == 1" class="content-text">
            <rich-text :nodes="baseData.details.content ? baseData.details.content : '-'"></rich-text>
          </view>
          <up-image
            v-show="baseData.details.type == 2"
            :src="imgUrl + '/' + baseData.details.content"
            mode="widthFix"
            class="content-image"
          ></up-image>
        </view>
      </view>
    </up-popup>

    <!-- Telegram  -->
    <a :href="baseData.aircraftUrl" target="_blank">
      <img class="telegram-fixed-icon" src="@/static/teltgram.png" />
    </a>
  </view>
</template>

<style lang="scss" scoped>
.message-container {
  width: 100%;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;

  // 
  .bg-decoration {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    overflow: hidden;

    .circle {
      position: absolute;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.1);
      animation: float 6s ease-in-out infinite;

      &.circle-1 {
        width: 200rpx;
        height: 200rpx;
        top: 10%;
        left: 10%;
        animation-delay: 0s;
      }

      &.circle-2 {
        width: 150rpx;
        height: 150rpx;
        top: 30%;
        right: 20%;
        animation-delay: 2s;
      }

      &.circle-3 {
        width: 100rpx;
        height: 100rpx;
        top: 75%;
        left: 20%;
        animation-delay: 4s;
      }
    }

    .floating-shape {
      position: absolute;
      font-size: 60rpx;
      opacity: 0.3;
      animation: bounce 8s ease-in-out infinite;

      &.shape-1 {
        top: 25%;
        right: 15%;
        animation-delay: 1s;
      }

      &.shape-2 {
        top: 60%;
        left: 15%;
        animation-delay: 3s;
      }

      &.shape-3 {
        top: 80%;
        right: 25%;
        animation-delay: 5s;
      }
    }
  }


  // 
  .tabs-section {
    margin: 80rpx 20rpx 0;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(20px);
    border-radius: 25rpx;
    padding: 20rpx;
    box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
    position: relative;
    z-index: 10;

    ::v-deep .u-tabs {
      .u-tabs__wrapper__nav__item {
        flex: 1 !important;
        font-weight: 600;
      }
    }
  }

  // 
  .message-list-section {
    flex: 1;
    margin: 0 20rpx;
    margin-top: 40rpx;
    position: relative;
    z-index: 2;

    .list-container {
      background: rgba(255, 255, 255, 0.95);
      backdrop-filter: blur(20px);
      border-radius: 25rpx;
      padding: 10rpx;
      min-height: 60vh;
      box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);

      .message-item {
        display: flex;
        align-items: center;
        padding: 30rpx;
        margin: 10rpx;
        background: white;
        border-radius: 20rpx;
        box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.08);
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-5rpx);
          box-shadow: 0 10rpx 25rpx rgba(0, 0, 0, 0.15);
        }

        .item-icon {
          margin-right: 25rpx;

          .icon-circle {
            width: 80rpx;
            height: 80rpx;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea, #764ba2);
            display: flex;
            align-items: center;
            justify-content: center;

            .icon-text {
              font-size: 32rpx;
            }
          }
        }

        .item-content {
          flex: 1;

          .message-title {
            font-size: 28rpx;
            color: #333;
            font-weight: 600;
            margin-bottom: 10rpx;
            line-height: 1.4;
          }

          .message-preview {
            font-size: 24rpx;
            color: #666;
            margin-bottom: 10rpx;
            line-height: 1.4;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .message-time {
            font-size: 22rpx;
            color: #999;
          }
        }

        .item-status {
          .unread-indicator {
            width: 20rpx;
            height: 20rpx;
            border-radius: 50%;
            background: linear-gradient(135deg, #fe8400, #ff5800);
            box-shadow: 0 4rpx 12rpx rgba(254, 132, 0, 0.4);
          }
        }
      }

      .empty-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 100rpx 0;

        .empty-icon {
          font-size: 120rpx;
          margin-bottom: 30rpx;
          opacity: 0.3;
        }

        .empty-text {
          font-size: 28rpx;
          color: #999;
        }
      }

      .bottom-status {
        text-align: center;
        padding: 40rpx 0;

        .loading-text {
          font-size: 26rpx;
          color: #999;
        }
      }
    }
  }
}

// 
.detail-container {
  padding: 40rpx;
  height: 100%;
  display: flex;
  flex-direction: column;

  .detail-header {
    margin-bottom: 30rpx;

    .detail-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 10rpx;
    }

    .detail-time {
      font-size: 24rpx;
      color: #999;
    }
  }

  .detail-content {
    flex: 1;
    overflow-y: auto;

    .content-text {
      font-size: 28rpx;
      color: #333;
      line-height: 1.6;
    }

    .content-image {
      width: 100%;
      border-radius: 15rpx;
      margin-top: 20rpx;
    }
  }
}



// 
@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-20px); }
}

@keyframes bounce {
  0%, 100% { transform: translateY(0px) rotate(0deg); }
  50% { transform: translateY(-10px) rotate(5deg); }
}

@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); }
}
</style>